//
//  ZZJLViewController.swift
//  demo
//
//  Created by toro宇 on 2020/2/13.
//  Copyright © 2020 CodeYu. All rights reserved.
//

import UIKit
import SnapKit


class ZZJLViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource {
   
    lazy var dataAry : Array<Dictionary<String, Any>> = {
        var ary = Array<Dictionary<String, Any>>()
        let path = Bundle.main.path(forResource: "data", ofType: "json")
        let url = URL(fileURLWithPath: path!)
        // 带throws的方法需要抛异常
        do {
            /*
             * try 和 try! 的区别
             * try 发生异常会跳到catch代码中
             * try! 发生异常程序会直接crash
             */
            let data = try Data(contentsOf: url)
            let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            let jsonArr = jsonData as! NSArray
            
            for dict in jsonArr {
                print(dict)
//                guard let model = MWMapDecoder<ZZJLModel>().decoderDictionary(value: dict as! Dictionary<String, Any>) else {
//                    continue
//                }
                ary.append(dict as! [String : Any]);
            }
        } catch let error as Error? {
            print("读取本地数据出现错误!",error)
        }
        
        
        return ary
    }()
    lazy var nav = HZCustomNavigationBar.customNavigationBar()
    var dateFilterView : DateFilterView?
    var selectedDateStr : String?
    
    
    let timeFilterBtn = UIButton(type: .custom)
    lazy var filterView : UIView = {
        let view = UIView();
        view.backgroundColor = .white;
        
        view .addSubview(timeFilterBtn)
        timeFilterBtn.snp.makeConstraints({ (make) in
            (make as ConstraintMaker).left.equalTo(view).offset(10)
            (make as ConstraintMaker).centerY.equalToSuperview()
        })
        timeFilterBtn.setTitle("20202020", for: .normal)
        timeFilterBtn.setTitleColor(UIColor.gray, for: .normal)
        timeFilterBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        timeFilterBtn.setImage(UIImage(named: "arrow"), for: .normal)
        timeFilterBtn.jk_setImagePosition(.LXMImagePositionRight, spacing: 5)
        timeFilterBtn.addTarget(self, action: #selector(timeFilterAction(_:)), for: .touchUpInside)
        
        let moneyLab = UILabel()
        view.addSubview(moneyLab)
        moneyLab.snp.makeConstraints({ (make) in
            (make as ConstraintMaker).right.equalTo(view).offset(-10)
            (make as ConstraintMaker).centerY.equalToSuperview()
        })
        moneyLab.textColor = UIColor.gray
        moneyLab.font = UIFont.systemFont(ofSize: 13)
        moneyLab.text = "消费: 202019"
        return view;
    }()
    
    
    lazy var tab : UITableView = {
        let tableView = UITableView.init(frame: CGRect.init(), style: .grouped)
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.register(ZZJLCell.self, forCellReuseIdentifier: "ZZJLCell")
        tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "Header")
        return tableView;
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: "f5f5f5")
        initNav()
        view.addSubview(filterView)
        filterView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(nav.snp_bottomMargin)
            make.height.equalTo(45)
        }
        view.addSubview(tab)
        tab.snp.makeConstraints { (make) in
            make.top.equalTo(filterView.snp_bottomMargin)
            make.left.right.bottom.equalToSuperview()
        }
        tab.delegate = self
        tab.dataSource = self
    
        
        // Do any additional setup after loading the view.
    }
    // 初始化导航栏
    func initNav() {
        view.addSubview(nav)
        nav.barBackgroundColor = UIColor(hex: "fbfbfb")
        nav.shadowImageHidden = false
        /* 闭包 相当于block
         { (参数) -> (返回值) in
         
         }
         */
        nav.hz.setItemsToLeft([HZNavigationBarItem.create(normalImage: "back", barItemClickHandler: { (item) in
            self.navigationController?.popViewController(animated: true)
        }), HZNavigationBarItem.create(normalTitle: "转帐记录", barItemClickHandler: {
            (item) in
        })])
    }
    // 初始化UI
    func initCustonUI() {
        
    }
    
    // MARK: -Action
    @objc  func timeFilterAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if(sender.isSelected){
            timeFilterBtn.setTitleColor(UIColor.red, for: .normal)
            dateFilterView =  DateFilterView.dateFilterView(dataAry: [["title":"202010"],["title":"202020"],["title":"202030"]], defaultStr: selectedDateStr) { (dateStr) in
                sender.isSelected = false
                self.timeFilterBtn.setTitleColor(UIColor.gray, for: .normal)
                if((dateStr) != nil){
                    self.selectedDateStr = dateStr
                    self.timeFilterBtn.setTitle(dateStr, for: .normal)
                }
                
            }
            view.addSubview(dateFilterView!)
            dateFilterView?.snp.makeConstraints({ (make) in
                make.left.right.bottom.equalToSuperview()
                make.top.equalTo(filterView.snp_bottomMargin)
            })
        
        }else{
            timeFilterBtn.setTitleColor(UIColor.gray, for: .normal)
            dateFilterView?.removeFromSuperview()
        }
    }
    
    // MARK: -Delegate
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataAry.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var dic = dataAry[section]
        return (dic["content"] as! NSArray).count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ZZJLCell", for: indexPath) as! ZZJLCell

        let sectionDic = dataAry[indexPath.section]
        let dic = (sectionDic["content"] as! NSArray)[indexPath.row] as! Dictionary<String, String>
        cell.logoImg.image = UIImage(named: "biaozhi")
        cell.titleLab.text = dic["company"]
        cell.typeLab.text = dic["type"]
        cell.moneyLab.text = dic["money"]
        cell.timeLab.text = dic["time"]
        return cell;
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView =  tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header") as! UITableViewHeaderFooterView
        for subView in headerView.subviews {
            subView.removeFromSuperview()
        }
        let lab = UILabel().then {
            $0.textColor = UIColor.init(hex: "a5a5a5")
            $0.font = UIFont.systemFont(ofSize: 12)
        }
        headerView.addSubview(lab)
        lab.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        
        let sectionDic = dataAry[section]
        lab.text = sectionDic["dataTime"] as? String
        
        return headerView
    }
    
    // 取消section尾部
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    
    


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
